package com.xnyzc.lhy.order.controller.auth;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.xnyzc.lhy.common.entity.Qd;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.util.IDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 后台管理用户用户登录验证码
 */
@RestController
@RequestMapping("/oa/cmsUser")
public class KaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${global.kaptcha.codeTimeout}")
    private Integer timeout;

    /**
     * 生成验证码
     */
    @GetMapping("/getLoginCheckCode")
    public Rv getLoginCheckCode(String time)
            throws ServletException, IOException {

        // 生产验证码字符串
        String createText = defaultKaptcha.createText();
        // 生成图片验证码
        ByteArrayOutputStream outputStream = null;
        outputStream = new ByteArrayOutputStream();
        // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
        BufferedImage challenge = defaultKaptcha.createImage(createText);
        ImageIO.write(challenge, "jpg", outputStream);

        // 生成captcha的ID
        long kaptchaId = IDUtil.nextId();
        redisTemplate.opsForValue().set(String.valueOf(kaptchaId), createText);
        redisTemplate.expire(String.valueOf(kaptchaId), timeout, TimeUnit.SECONDS);

        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return Rv.wrap(Qd.create().add("kaptchaId", kaptchaId).add("img", encoder.encode(outputStream.toByteArray())));

    }

}
